package io.github.yidasanqian.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Linyu Chen
 */
@Slf4j
@RequestMapping("file")
@Controller
public class FileController {

    @Value("${storaged.server.url}")
    private String imageServerUrl;

    @PostMapping("/pic/upload")
    @ResponseBody
    public Map<String, Object> upload(MultipartFile uploadFile) {
        Map<String, Object> result = new HashMap<>();
        String originName = uploadFile.getOriginalFilename();
        String extName = originName.substring(originName.lastIndexOf(".") + 1);
        FastDFSClient fastDFSClient = null;
        try {
            fastDFSClient = new FastDFSClient("classpath:fdfs_client.conf");
            String url = fastDFSClient.uploadFile(uploadFile.getBytes(), extName);
            url = imageServerUrl + url;
            log.debug("上传回显的文件地址：{}", url);
            result.put("error", 0);
            result.put("url", url);
        } catch (Exception e) {
            log.error("上传图片异常！", e);
            result.put("error", 0);
            result.put("message", "上传图片失败！");
        }
        return result;
    }
}
